package net.htjs.juc.printorder;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 打印先后顺序 ReentrantLock版本
 */
@Slf4j
public class ReentrantLockDemo {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();
    static boolean runned = false;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try{
                lock.lock();
                while (!runned) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("1");
            } finally {
                lock.unlock();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            try{
                lock.lock();
                runned = true;
                condition.signal();
                log.debug("2");
            } finally {
                lock.unlock();
            }
        }, "t2");
        t1.start();
        t2.start();
    }
}
